package com.bestcem.xm.user.controller;

import cn.hutool.core.io.unit.DataSize;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.common.core.enums.ResourceErrorCodeEnum;
import com.bestcem.xm.user.controller.vo.FileInfoVO;
import com.bestcem.xm.user.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * @author zhangfeng <feng.zhang@idiaoyan.com>
 * @version v1.0
 * @date 2022/7/17 21:24
 */
@RestController
@Slf4j
@RequestMapping(value = "/user")
public class FileOperateController {
    @Value("${app.user.max-file-size:5mb}")
    private String maxFileSize;
    @Resource
    private FileService fileService;

    @PostMapping(value = "/upload")
    public XmResultJson<FileInfoVO> uploadFile(@RequestParam(name = "file") MultipartFile file) {
        if (file.getSize() == 0 || file.getSize() > DataSize.parse(maxFileSize).toBytes()) {
            return XmResultJson.fail(ResourceErrorCodeEnum.INVALID_FORMAT, "上传文件大小不在允许范围内");
        }
        ServiceResult<FileInfoVO> result = fileService.uploadFile(file);
        if (result.isSuccess()) {
            return XmResultJson.success(result.getData());
        }
        return XmResultJson.fail(result.getErrorData(), result.getMsg());
    }
}
